package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
public class RecommedApiImpl implements RecommedApi {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private UserLikeApi userLikeApi;

    /**
     * 获取一个今日佳人
     *
     * @param userId
     * @return
     */
    @Override
    public RecommendUser getRecommendUser(Long userId) {
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(Sort.by(Sort.Order.desc("date"))).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * 获取系统推荐的今日佳人
     *
     * @param userId
     * @return
     */
    @Override
    public List<RecommendUser> getAllTodayBest(Integer page, Integer pageSize, Long userId) {
        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);
        return mongoTemplate.find(query, RecommendUser.class);
    }

    /**
     * 根据用户id和有缘人id获取缘分值
     *
     * @param userId
     * @param fateId
     * @return
     */
    @Override
    public Double getFatcvalue(Long userId, Long fateId) {

        Query query = Query.query(Criteria.where("userId").is(fateId).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 88d;
        }
        return recommendUser.getScore();
    }

    /**
     * 查询探花列表，查询时需要排除不喜欢列表用户
     *
     * @param userId
     * @param count
     * @return
     */
    @Override
    public List<RecommendUser> queryCardList(Long userId, Integer count) {
        PageRequest pageRequest = PageRequest.of(0, count, Sort.by(Sort.Order.desc("score")));
        //排除喜欢或者不喜欢的用户列表
        List<Long> list = new ArrayList<>();
        list.addAll(userLikeApi.queryLikeList(userId));
        list.addAll(userLikeApi.queryNotLikeList(userId));
        Criteria criteria = Criteria.where("toUserId").is(userId);
        if (CollUtil.isNotEmpty(list)) {
            criteria.andOperator(Criteria.where("userId").nin(list));
        }
        Query query = Query.query(criteria).with(pageRequest);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        return recommendUsers;
    }


}
